package com.example.demo.domain.category;

import com.example.demo.domain.category.repository.CategoryRepository;
import lombok.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 * 应用分类
 *
 * @author yingjianhua
 */
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@EqualsAndHashCode
@Getter
@Setter
@Configuration
@Entity
public class Category {

    private static CategoryRepository repository;
    private static CategorySortService sortService;

    @Autowired
    private void setCategoryRepository(CategoryRepository repository) {
        Category.repository = repository;
    }

    @Autowired
    private void setCategorySortService(CategorySortService sortService) {
        Category.sortService = sortService;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    /**
     * 应用分类的名称
     * 名称是唯一的不能重复
     */
    private String name;

    /**
     * 该应用分类是否启用
     * 是否启用只关系到应用是否能选择该分类，已经选择了的不用额外处理，该逻辑判断在应用中
     */
    private Boolean enable = false;

    /**
     * 排序号
     */
    private Integer sort = 0;

    public Category(String name) {
        this.setName(name);
        this.sort = sortService.generateSort();
    }

    public void setName(String name) {
        if (name.equals(this.name)) {
            return;
        }
        // 这里需要做唯一性判断
        if (repository.findByName(name).isPresent()) {
            throw new RuntimeException("该名称的应用分类已经存在");
        }
        this.name = name;
    }

    public void setEnable(boolean enable) {
        if (this.enable == enable) {
            return;
        }
        if (enable) {
            // 如果该分类下没有应用， 是不能开启的 TODO
        }
        this.enable = enable;
    }

    @Override
    public String toString() {
        return "Category{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", enable=" + enable +
                ", sort=" + sort +
                '}';
    }
}


